import { useState, useCallback } from 'react';

    // API基础URL配置
    const API_BASE_URL = process.env.NODE_ENV === 'production' 
      ? 'https://api.example.com/v1' 
      : 'http://localhost:5000/api/v1';

    /**
     * 自定义Hook，用于处理API请求
     * @returns {Object} 包含请求方法和状态的对象
     */
    const useApi = () => {
      const [loading, setLoading] = useState(false);
      const [error, setError] = useState(null);

      /**
       * 发送请求的通用方法
       * @param {string} endpoint - API端点
       * @param {Object} options - fetch选项
       * @returns {Promise<any>} 响应数据
       */
      const sendRequest = useCallback(async (endpoint, options = {}) => {
        setLoading(true);
        setError(null);
        
        try {
          // 添加默认headers
          const headers = {
            'Content-Type': 'application/json',
            ...options.headers,
          };

          // 从localStorage获取token（如果有）
          const token = localStorage.getItem('authToken');
          if (token) {
            headers['Authorization'] = `Bearer ${token}`;
          }
          console.log("请求数据")
          const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            ...options,
            headers,
          });

          // 处理非2xx响应
          if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.message || `请求失败: ${response.status}`);
          }

          // 解析响应
          const data = await response.json();
          return data;
        } catch (err) {
          setError(err.message || '请求过程中发生错误');
          throw err;
        } finally {
          setLoading(false);
        }
      }, []);

      /**
       * GET请求
       * @param {string} endpoint - API端点
       * @param {Object} options - 额外的fetch选项
       * @returns {Promise<any>} 响应数据
       */
      const get = useCallback((endpoint, options = {}) => {
        return sendRequest(endpoint, {
          method: 'GET',
          ...options,
        });
      }, [sendRequest]);

      /**
       * POST请求
       * @param {string} endpoint - API端点
       * @param {Object} data - 要发送的数据
       * @param {Object} options - 额外的fetch选项
       * @returns {Promise<any>} 响应数据
       */
      const post = useCallback((endpoint, data, options = {}) => {
        return sendRequest(endpoint, {
          method: 'POST',
          body: JSON.stringify(data),
          ...options,
        });
      }, [sendRequest]);

      /**
       * PUT请求
       * @param {string} endpoint - API端点
       * @param {Object} data - 要发送的数据
       * @param {Object} options - 额外的fetch选项
       * @returns {Promise<any>} 响应数据
       */
      const put = useCallback((endpoint, data, options = {}) => {
        return sendRequest(endpoint, {
          method: 'PUT',
          body: JSON.stringify(data),
          ...options,
        });
      }, [sendRequest]);

      /**
       * DELETE请求
       * @param {string} endpoint - API端点
       * @param {Object} options - 额外的fetch选项
       * @returns {Promise<any>} 响应数据
       */
      const del = useCallback((endpoint, options = {}) => {
        return sendRequest(endpoint, {
          method: 'DELETE',
          ...options,
        });
      }, [sendRequest]);

      /**
       * 上传文件
       * @param {string} endpoint - API端点
       * @param {FormData} formData - 包含文件的FormData对象
       * @param {Function} progressCallback - 进度回调函数
       * @returns {Promise<any>} 响应数据
       */
      const uploadFile = useCallback(async (endpoint, formData, progressCallback = null) => {
        setLoading(true);
        setError(null);
        
        try {
          // 从localStorage获取token（如果有）
          const token = localStorage.getItem('authToken');
          const headers = {};
          
          if (token) {
            headers['Authorization'] = `Bearer ${token}`;
          }

          // 使用XMLHttpRequest来支持进度监控
          return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            
            xhr.open('POST', `${API_BASE_URL}${endpoint}`);
            
            // 设置headers
            if (token) {
              xhr.setRequestHeader('Authorization', `Bearer ${token}`);
            }
            
            // 监听进度事件
            if (progressCallback) {
              xhr.upload.onprogress = (event) => {
                if (event.lengthComputable) {
                  const percentComplete = Math.round((event.loaded / event.total) * 100);
                  progressCallback(percentComplete);
                }
              };
            }
            
            xhr.onload = function() {
              if (xhr.status >= 200 && xhr.status < 300) {
                const response = JSON.parse(xhr.responseText);
                resolve(response);
              } else {
                reject(new Error(`上传失败: ${xhr.status}`));
              }
              setLoading(false);
            };
            
            xhr.onerror = function() {
              setError('上传过程中发生网络错误');
              reject(new Error('网络错误'));
              setLoading(false);
            };
            
            xhr.send(formData);
          });
        } catch (err) {
          setError(err.message || '上传过程中发生错误');
          setLoading(false);
          throw err;
        }
      }, []);

      return {
        loading,
        error,
        get,
        post,
        put,
        delete: del, // 'delete' 是保留字，所以使用 'del' 作为函数名，但导出为 'delete'
        uploadFile,
      };
    };

    export default useApi;
